package org.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.example.Users;
import org.example.UserMapper;
import org.example.domain.dto.LoginDto;
import org.example.domain.model.Result;
import org.example.service.IUserService;
import org.example.utils.JwtUtils;
import org.example.utils.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements IUserService {

    private UserMapper userMapper;
    private PasswordEncoder passwordEncoder;
    private JwtUtils jwtUtils;

    public UserServiceImpl(UserMapper userMapper, PasswordEncoder passwordEncoder, JwtUtils jwtUtils) {
        this.userMapper = userMapper;
        this.passwordEncoder = passwordEncoder;
        this.jwtUtils = jwtUtils;
    }

    @Override
    public Result login(LoginDto loginDto) {
        // TODO 验证用户名和密码对不对，如果正确要颁发 access_token 和 refresh_token
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", loginDto.getUsername());

        Users users = userMapper.selectOne(queryWrapper);

        /**
         * passwordEncoder(String passwordRaw, String dbPassword)
         */
        if(null == users || !passwordEncoder.matches(loginDto.getPassword(), users.getPassword())) {
            return Result.buildFailure("用户名或密码错误");
        }else {
            Map<String, String> tokens = new HashMap<>();
            String username = loginDto.getUsername();
            tokens.put(JwtUtils.ACCESS_TOKEN_KEY, jwtUtils.createAccessToken(username));
            tokens.put(JwtUtils.REFRESH_TOKEN_KEY, jwtUtils.createRefreshToken(username));
            return Result.buildSuccess(tokens);
        }
    }
}
